/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.swak.stroage;

import java.nio.ByteBuffer;
import java.util.Deque;
import java.util.concurrent.ConcurrentLinkedDeque;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.sun.jna.NativeLong;
import com.sun.jna.Pointer;

import sun.nio.ch.DirectBuffer;

@SuppressWarnings("restriction")
public class TransientStorePool {
	protected static final Logger log = LoggerFactory.getLogger(TransientStorePool.class);
	private final int poolSize;
	private final int fileSize;
	private final Deque<ByteBuffer> availableBuffers;
	private boolean transientStorePoolEnable;

	public TransientStorePool(boolean transientStorePoolEnable, int poolSize, int fileSize) {
		this.transientStorePoolEnable = transientStorePoolEnable;
		this.poolSize = poolSize;
		this.fileSize = fileSize;
		this.availableBuffers = new ConcurrentLinkedDeque<>();
	}

	/**
	 * It's a heavy init method.
	 */
	public void init() {
		for (int i = 0; i < poolSize; i++) {
			ByteBuffer byteBuffer = ByteBuffer.allocateDirect(fileSize);

			final long address = ((DirectBuffer) byteBuffer).address();
			Pointer pointer = new Pointer(address);
			LibC.INSTANCE.mlock(pointer, new NativeLong(fileSize));

			availableBuffers.offer(byteBuffer);
		}
	}

	public void destroy() {
		for (ByteBuffer byteBuffer : availableBuffers) {
			final long address = ((DirectBuffer) byteBuffer).address();
			Pointer pointer = new Pointer(address);
			LibC.INSTANCE.munlock(pointer, new NativeLong(fileSize));
		}
	}

	public void returnBuffer(ByteBuffer byteBuffer) {
		byteBuffer.position(0);
		byteBuffer.limit(fileSize);
		this.availableBuffers.offerFirst(byteBuffer);
	}

	public ByteBuffer borrowBuffer() {
		ByteBuffer buffer = availableBuffers.pollFirst();
		if (availableBuffers.size() < poolSize * 0.4) {
			log.warn("TransientStorePool only remain {} sheets.", availableBuffers.size());
		}
		return buffer;
	}

	public int availableBufferNums() {
		if (transientStorePoolEnable) {
			return availableBuffers.size();
		}
		return Integer.MAX_VALUE;
	}
}
